package com.zzzzzz.core.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.zzzzzz.common.exception.NoSuchTicketException;
import com.zzzzzz.common.util.StringPool;
import com.zzzzzz.core.exception.SystemException;
import com.zzzzzz.core.model.po.Ticket;

@Repository
public class TicketDao extends BaseDao {
	
	private static final String ADD = "insert into ticket(ticket_id, key_, class_name_id, class_pk, create_date, expiration_date, category) values(:ticketId, :key, :classNameId, :classPK, :createDate, :expirationDate, :category)";
	
	private static final String DELETE = "delete from ticket where key_ = ?";
	
	private static final String FIND_BY_KEY = "select * from ticket where key_ = ?";

	private static final String FIND_BY_KEY_AND_CATEGORY = "select * from ticket where key_ = ? and category = ?";

	private static final String _NO_SUCH_ENTITY_WITH_KEY = "No Ticket exists with the key {";
	
	protected class TicketRowMapper implements RowMapper<Ticket> {
//		@Override
		public Ticket mapRow(ResultSet rs, int rn) throws SQLException {
			Ticket ticket = new Ticket();
			ticket.setTicketId(rs.getLong("ticket_id"));
			ticket.setClassNameId(rs.getLong("class_name_id"));
			ticket.setClassPK(rs.getLong("class_pk"));
			ticket.setKey(rs.getString("key_"));
			ticket.setCreateDate(rs.getDate("create_date"));
			ticket.setExpirationDate(rs.getDate("expiration_date"));
			return ticket;
		}
	}
	
	public Ticket add(Ticket ticket) throws SystemException {
		try{
			long ticketId = updateForLongKey(ADD, ticket);
			ticket.setTicketId(ticketId);
			return ticket;
		}catch (Exception e) {
			throw processException(e);
		}
	}
	
	public void delete(String key) throws SystemException {
		try{
			update(DELETE, key);
		}catch (Exception e) {
			throw processException(e);
		}
	}
	
	public Ticket findByKey(String key) throws NoSuchTicketException, SystemException {
		Ticket ticket = null;
		try{
			ticket = findOne(FIND_BY_KEY, new TicketRowMapper(), key);
		}catch(Exception e) {
			throw processException(e);
		}
		if(ticket == null) {
			throw new NoSuchTicketException(_NO_SUCH_ENTITY_WITH_KEY + "key=" + key + StringPool.CLOSE_CURLY_BRACE);
		}
		return ticket;
	}
	
	public Ticket findByKeyAndCategory(String key, String category) throws NoSuchTicketException, SystemException {
		Ticket ticket = null;
		try{
			ticket = findOne(FIND_BY_KEY_AND_CATEGORY, new TicketRowMapper(), key, category);
		}catch(Exception e) {
			throw processException(e);
		}
		if(ticket == null) {
			throw new NoSuchTicketException(_NO_SUCH_ENTITY_WITH_KEY + "key=" + key + " And category=" + category + StringPool.CLOSE_CURLY_BRACE);
		}
		return ticket;
	}

}
